<?php

class UserSettingsForm extends SettingsForm
{

    public function configure()
    {
        $this->setWidget('password', new sfWidgetFormInputPassword());
        $this->setWidget('confirm_password', new sfWidgetFormInputPassword());
        $this->setWidget('change_password', new sfWidgetFormInputCheckbox(array('value_attribute_value' => 1)));

        // validators
        $this->getValidator('password')->setOption('required', false);
        $this->setValidator('confirm_password', new sfValidatorString(array('required' => false)));
        // vlaidate email
        $this->setValidator('email', new sfValidatorRegex(array('pattern'    => '/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',
                    'min_length' => 6, 'max_length' => 255, 'required'   => true),
                        array(
                            'invalid'    => 'Invalid email format.',
                            'required'   => 'Please enter required field.',
                            'min_length' => 'Invalid email format.',
                            'max_length' => 'Invalid email format.',
                )));
        $this->validatorSchema->setOption('allow_extra_fields', true);
        $this->validatorSchema->setOption('filter_extra_fields', false);
        $this->useFields(array('username', 'email', 'change_password', 'password', 'confirm_password'));
        $this->mergePostValidator(new sfValidatorCallback(array('callback' => array($this, 'checkPassword'))));
        $this->addFormatter('customFormatter');
    }

    public function doUpdateObject($values)
    {
        if (!isset($values['change_password']))
        {
            unset($values['password']);
        }
        parent::doUpdateObject($values);
    }

    public function checkPassword($validator, $values)
    {
        $error = array();
        //check user exist (email or username)
        if (isset($values['change_password']))
        {
            if ($values['password'])
            {
                if (strlen($values['password']) < 6)
                {
                    $error['password'] = new sfValidatorError($validator, 'Filed data is too short (6 characters min)');
                }
                if ($values['password'] && $values['password'] != $values['confirm_password'])
                {
                    $error['confirm_password'] = new sfValidatorError($validator, 'New passwords do not match');
                }
            }
            else
            {
                $error['password'] = new sfValidatorError($validator, 'Please insert required data');
            }
        }
        if (count($error) >= 1)
        {
            // throw error
            throw new sfValidatorErrorSchema($validator, $error);
        }
        // return values
        return $values;
    }

}